﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using IHISCETeim.Model;
using IHISCETeim.BLL;
using IHISCETeim.Library;
using FineUI;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Data;


namespace IHISCETeim.Web.AgentSys.SvrMgr
{
    public partial class AddAgentQlty : AgentPageBase
    {
        protected override Permission[] PowerKey
        {
            get
            {
                return new Permission[] { Permission.新增 };
            }
        }
        protected override string DWZRef
        {
            get { return "AddAgentQlty"; }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }
        private void LoadData()
        {
            btnClose.OnClientClick = GetCloseActiveTabScript();

            IssueDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
            this.AgentName.Text = User.Department;
            OUserInfo svrUser = OUserController.GetById(base.User.SrvActUserId);
            SvrInfo.Text = string.Format("{0} {1}", svrUser.RealName, svrUser.Mobile);
            //// 初始化用户所属部门　经销商
            InitAgentQltyPartsDate();
        }
        #region 初始化配件数量
        /// <summary>
        /// 初始化配件数量
        /// </summary>
        private void InitAgentQltyPartsDate()
        {
           // this.grd
            this.grdAgentQltyParts.DataSource = GetClassDataTable();
            this.grdAgentQltyParts.DataBind();
        }
        protected DataTable GetClassDataTable()
        {
            DataTable table = new DataTable();
            table.Columns.Add(new DataColumn("Id", typeof(int)));          
            for (int rowindex = 0; rowindex < 20; rowindex++)
            {
                DataRow row = table.NewRow();
                row[0] = rowindex;
                table.Rows.Add(row);
            }
            

          
            return table;
        }
        #endregion

        protected void filePhoto1_FileSelected(object sender, EventArgs e)
        {
            FineUI.FileUpload FileUpladControl = sender as FineUI.FileUpload;
            string cIndex = FileUpladControl.EmptyText;
            FineUI.Image imgRelativelyControl = Panel4.FindControl("imgRelatively" + cIndex) as FineUI.Image;



            if (FileUpladControl.HasFile)
            {
                string fileName = FileUpladControl.ShortFileName;

                if (!ValidateFileType(fileName))
                {
                    Alert.Show("无效的文件类型！");
                    return;
                }


                fileName = fileName.Replace(":", "_").Replace(" ", "_").Replace("\\", "_").Replace("/", "_");
                fileName = DateTime.Now.Ticks.ToString() + "_" + fileName;

                string path = GetUpLoadFilePath(User.Department);
                FileUpladControl.SaveAs(Server.MapPath(path + fileName));

                imgRelativelyControl.ImageUrl = path + fileName;

                // 清空文件上传组件
                FileUpladControl.Reset();
                
            }
        }

        protected void fileOther_FileSelected(object sender, EventArgs e)
        {
            //if (fileOther.HasFile)
            //{
            //    string fileName = fileOther.ShortFileName;

            //    if (!ValidateFileType(fileName))
            //    {
            //        Alert.Show("无效的文件类型！");
            //        return;
            //    }


            //    fileName = fileName.Replace(":", "_").Replace(" ", "_").Replace("\\", "_").Replace("/", "_");
            //    fileName = DateTime.Now.Ticks.ToString() + "_" + fileName;

            //    string path = GetUpLoadFilePath(User.Department);
            //    fileOther.SaveAs(Server.MapPath(path + fileName));

            //    fileOther.Label = path + fileName;

            //    // 清空文件上传组件
            //    fileOther.Reset();
            //}
        }

        /// <summary>
        /// 输完机号后,自动从保修卡里获取相应信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void SerialNumber_Blur(object sender, EventArgs e)
        {

            string _SerialNumber = this.SerialNumber.Text.Trim();
            UWarrantyCardInfo obj = UWarrantyCardController.GetBySerialNumber(_SerialNumber);
            //if (obj.UWCID <= 0)
            //{
            //    Alert.Show(String.Format("对不起,机号{0}不存在,请重新输入.", _SerialNumber));
            //    this.btnSaveClose.Enabled = false;
            //    return;
            //}
            //if (obj.AgentName != this.AgentName.Text)
            //{
            //    Alert.Show(String.Format("对不起,机号{0}不属于您的,不能进行品情提报.如有问题,请联系IHISCE服务部.",_SerialNumber));
            //    this.btnSaveClose.Enabled = false;
            //    return;
            //}
            this.btnSaveClose.Enabled = true;
            this.CustomerName.Text = obj.CustomerName;
            this.CustomerMobile.Text = obj.CustomerMobile;
            this.IntoDate.Text = obj.IntoDate.ToString("yyyy-MM-dd");
            this.IntoAddress.Text = obj.IntoAddress;
            this.FaultDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
            this.MachineType.Text = obj.MachineType;

            this.IntoConditi.SelectedValue = obj.IntoConditi;

            this.IntoSpecial.SelectedValue = GetDefaultIntoSpecial(obj.IntoSpecial); 
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSaveClose_Click(object sender, EventArgs e)
        {
            AgentQltyInfo obj = new AgentQltyInfo();
            obj.IssueDate =Convert.ToDateTime( this.IssueDate.Text);
            obj.SerialNumber = this.SerialNumber.Text;
            obj.MachineType = this.MachineType.Text;
            obj.CustomerName = this.CustomerName.Text;
            obj.CustomerMobile = this.CustomerMobile.Text;
            obj.IntoDate = Convert.ToDateTime( this.IntoDate.Text);
            obj.IntoAddress = this.IntoAddress.Text;
            obj.FaultDate = Convert.ToDateTime( this.FaultDate.Text);
            obj.WorkHour =Convert.ToDecimal(  this.WorkHour.Text.Trim());
            obj.ReportUser = this.ReportUser.Text;
            obj.ReportTel = this.ReportTel.Text;
            obj.MacNature = this.MacNature.SelectedValue;
            obj.IntoConditi = this.IntoConditi.SelectedValue;
            obj.IntoSpecial = this.IntoSpecial.SelectedValue;
            obj.DamagePartsNumber = this.DamagePartsNumber.Text;
            obj.FaultDescription = this.HEFaultDescription.Text;
            obj.FaultReason = this.HEFaultReason.Text;
            obj.ProcessMode = this.HEProcessMode.Text;

            obj.IsVisit = false;
            obj.SvrResult ="";
            obj.SvrScheme ="";
            obj.PartsSendDate = "";
            obj.PartsSendType = "";

            obj.UserId =this.User.UserId;
            obj.AgentName =this.User.Department;
            obj.SrvActUserId = this.User.SrvActUserId;
            obj.SrvActRealName = OUserController.GetById(User.SrvActUserId).RealName;
            obj.SrvMangerUserId = AgentConfigController.SvrManagerUserId;
            obj.ClaimState = ClaimState.担当确认中.ToString();
            obj.RejectReason ="";
            obj.CancelReason = "";

            //加载图片信息
            //AgentQltyImgInfo imgObj = new AgentQltyImgInfo();
            List<AgentQltyImgInfo> imgList = new List<AgentQltyImgInfo>();
            //AgentQltyImgInfo imgObj = null;
            //for (int imgIndex = 1; imgIndex <= 6; imgIndex++)
            //{
            //    imgObj = new AgentQltyImgInfo();
            //    FineUI.Image imgRelativelyControl = Panel4.FindControl("imgRelatively" + imgIndex) as FineUI.Image;
            //    FineUI.TextBox ImgTitleControl = Panel4.FindControl("ImgTitle" + imgIndex) as FineUI.TextBox;
            //    imgObj.Title = ImgTitleControl.Text;
            //    imgObj.IMGRelatively = imgRelativelyControl.ImageUrl;
            //    imgObj.FileIndex = imgIndex;
            //    imgList.Add(imgObj);
            //}
            //imgObj = new AgentQltyImgInfo();
            //imgObj.Title = "其它文件";
            //// imgObj.IMGRelatively = fileOther.Label;
            //imgObj.FileIndex = 7;
            //imgList.Add(imgObj);

            //获取配件信息
            List<AgentQltyPartsInfo> partsList = new List<AgentQltyPartsInfo>();

          
            for (int i = 0, count = this.grdAgentQltyParts.Rows.Count; i < count; i++)
            {
                AgentQltyPartsInfo pobj = new AgentQltyPartsInfo();

                GridRow row = grdAgentQltyParts.Rows[i];
                System.Web.UI.WebControls.TextBox tbItemCode = (System.Web.UI.WebControls.TextBox)row.FindControl("tbItemCode");
                System.Web.UI.WebControls.TextBox tbDscription = (System.Web.UI.WebControls.TextBox)row.FindControl("tbDscription");
                FineUI.TextBox tbQuantity = (FineUI.TextBox)row.FindControl("Quantity");
                System.Web.UI.WebControls.DropDownList ddlPartsDemand = (System.Web.UI.WebControls.DropDownList)row.FindControl("ddlPartsDemand");

                if (!string.IsNullOrEmpty(tbItemCode.Text))
                {
                    pobj.ItemCode = tbItemCode.Text.Trim();
                    pobj.Dscription = tbDscription.Text.Trim();
                    pobj.Quantity = Convert.ToDecimal(tbQuantity.Text.Trim());
                    pobj.PartsDemand = ddlPartsDemand.SelectedValue;
                    pobj.LastPurPrice =Convert.ToDecimal( SBOController.GetOITMLastPurPrice(pobj.ItemCode));
                    partsList.Add(pobj);
                }
             
            }
            //处理上传数据
            char[] caSplit = new char[] { ',' };
            string[] imgRelativelyS = GetRequestValue<string>("imgRelatively", "").Split(caSplit);
            string XX = "";
            for (int index = 0; index < imgRelativelyS.Count(); index++)
            {
                if (imgRelativelyS[index] != "")
                {
                    XX += imgRelativelyS[index] + "<BR/>";
                }
            }
            Alert.Show(XX);
            return;
            if (AgentQltyController.Add(obj,imgList,partsList)>0)
            {
               // Alert.getsho;
               PageContext.Refresh();//.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
            }
            else
            {
                Alert.Show("添加品情表失败！", "提示", MessageBoxIcon.Error);
            }

           
        }

     
        


       
    }
}